from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
import os
import logging
from models import Project, Category
from forms import ProjectForm

class ListHandler(webapp.RequestHandler):

    def get(self):
        context = {
            'title': 'Projects',
            'section': 'Projects',
            'projects': Project.all()
        }
        path = os.path.join(os.path.dirname(__file__), 
            '../templates/projects.html')
        self.response.out.write(template.render(path, context))

class ItemHandler(webapp.RequestHandler):

    def get(self, key):
        project = Project.get(key)
        context = {
            'title': project.name,
            'section': 'Projects',
            'project': project,
            'in_progress': Category.gql('WHERE project = :1 and started = :2', project, True),
            'waiting': Category.gql('WHERE project = :1 and started = :2 and completed = :3', project, False, False),
            'completed': Category.gql('WHERE project = :1 and completed = :2', project, True),
        }
        path = os.path.join(os.path.dirname(__file__), 
            '../templates/project.html')
        self.response.out.write(template.render(path, context))

    def post(self, key):
        project = Project.get(key)
        data = ProjectForm(data=self.request.POST, instance=project)
        if data.is_valid():
            # Save the data, and redirect to the view page
            entity = data.save(commit=False)
            entity.put()
            self.redirect('/projects/%s/' % (entity.key(), ))
        else:
            context = {
                'title': 'Create a new Project',
                'form': data,
                'action': '/projects/edit/%s/' % (key, ),
            }
            path = os.path.join(os.path.dirname(__file__), '../templates/form.html')
            self.response.out.write(template.render(path, context))

class CreateHandler(webapp.RequestHandler):

    def get(self):
        context = {
            'title': 'Create a new Project',
            'form': ProjectForm(),
            'action': '/projects/create/',
        }
        path = os.path.join(os.path.dirname(__file__), '../templates/form.html')
        self.response.out.write(template.render(path, context))

    def post(self):
        data = ProjectForm(data=self.request.POST)
        if data.is_valid():
            # Save the data, and redirect to the view page
            entity = data.save(commit=False)
            entity.put()
            logging.debug('Finished saving')
            entity.reload_tickets()
            logging.debug('Finished reloading tickets')
            self.redirect('/projects/%s/' % (entity.key(), ))
        else:
            context = {
                'title': 'Create a new Project',
                'form': data,
                'action': '/projects/create/',
            }
            path = os.path.join(os.path.dirname(__file__), '../templates/form.html')
            self.response.out.write(template.render(path, context))

class EditHandler(webapp.RequestHandler):

    def get(self, key):
        project = Project.get(key)
        context = {
            'title': 'Edit Project %s' % (project.name, ),
            'form': ProjectForm(instance=project),
            'action': '/projects/%s/' % (project.key(), ),
        }
        path = os.path.join(os.path.dirname(__file__), '../templates/form.html')
        self.response.out.write(template.render(path, context))

class UpdateHandler(webapp.RequestHandler):
    def get(self):
        count = 0
        for project in Project.all():
            count = count + project.update_tickets()
        self.response.out.write(str(count))

class DeleteHandler(webapp.RequestHandler):

    def post(self, key):
        project = Project.get(key)
        project.delete()
        self.redirect('/projects/')
        
def main():
    application = webapp.WSGIApplication([
        ('/projects/', ListHandler),
        ('/projects/create/', CreateHandler),
        (r'/projects/edit/(.+)/', EditHandler),
        (r'/projects/delete/(.+)/', DeleteHandler),
        (r'/projects/update/', UpdateHandler),
        (r'/projects/(.+)/', ItemHandler),
        ], debug=True)
    util.run_wsgi_app(application)

if __name__ == '__main__':
    main()
